<template>
  <div class="app-container customer-div">


    <div style="margin-top:40px">
      <el-form :inline="true" :model="listQuery1" size="mini" label-width="100px">
        <el-form-item label="月份：">
          <el-date-picker
            style="width:150px;margin-right: 10px"
            size="mini"
            value-format="yyyy-MM"
            placeholder="请选择月份"
            v-model="listQuery1.month"
            type="month"
            align="right">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="品类：">
          <el-select size="mini" placeholder="请选择品类" clearable style="margin-right: 10px;width:150px"  v-model="listQuery1.goodsClass" >
            <el-option v-for="item in classList" :key="item.classId" :value="item.className" :label="item.className"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="厂家：" v-if="listQuery1.goodsClass">
          <el-input size="mini"  placeholder="请输入厂家" clearable style="width:150px;margin-right: 10px"  v-model="listQuery1.brandName"></el-input>
        </el-form-item>
        <el-form-item label="采购员：">
          <el-select size="mini"
                     collapse-tags
                     v-model="listQuery1.userIds" clearable
                     placeholder="请选择人员" multiple>
            <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="handleSearchList1()"
            type="primary">
            查询
          </el-button>
          <el-button
            :loading="btnLoading"
            v-if="pGoodsSaleNumAnalysisExport"
            @click="downloadExcel()"
            type="primary">
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--数据列表-->
    <div class="table-container">
      <el-table
        :row-class-name="tableRowClassName"
        v-loading="listLoading1"
        :data="tableData1"
        :span-method="objectSpanMethod"
        border
        height="500"
        style="width: 100%; margin-top: 20px">
        <el-table-column  label="品类" min-width="200" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.className != '合计'">{{scope.row.className}}</span>
            <span v-else style="font-weight: bold;">{{scope.row.className}}</span>
          </template>
        </el-table-column>
        <el-table-column  label="采购员" min-width="200" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.className != '合计'">{{scope.row.realName}}</span>
            <span v-else style="font-weight: bold;">{{scope.row.realName}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="厂家"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.brandName != '合计'">{{scope.row.brandName}}</span>
            <span style="font-weight: bold;" v-else>{{scope.row.brandName}}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="实际销量"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.className != '合计'&&scope.row.brandName != '合计' && scope.row.realName != '合计'">{{scope.row.goodsNum}}</span>
            <span v-else style="font-weight: bold;">{{scope.row | sumListfn(tableData1,'goodsNum',3)}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="目标销量"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.className != '合计'&&scope.row.brandName != '合计' && scope.row.realName != '合计'">{{scope.row.goodsNumTarget}}</span>
            <span v-else style="font-weight: bold;">{{scope.row | sumListfn(tableData1,'goodsNumTarget',3)}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="销量差额"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.className != '合计'&&scope.row.brandName != '合计' && scope.row.realName != '合计'" :style="{'color': scope.row.goodsNumDiff < 0 ? 'red' :'#606266'}">{{scope.row.goodsNumDiff}}</span>
            <span v-else style="font-weight: bold" :style="{'color': sumDifffn(scope.row,tableData1,'goodsNum','goodsNumTarget',3) < 0 ? 'red' :'#606266'}">{{ sumDifffn(scope.row,tableData1,'goodsNum','goodsNumTarget',3)}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="销量完成率"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.className != '合计'&&scope.row.brandName != '合计' && scope.row.realName != '合计'"
                  :style="{'color':scope.row.goodsNumRate<100 ? 'red':'#606266'}"
            >
              {{scope.row.goodsNumRate}}%
            </span>
            <span v-else
                  style="font-weight: bold;"
                  :style="{'color':sumRatefn(scope.row ,tableData1,'goodsNum','goodsNumTarget',0)<100 ? 'red':'#606266'}"
            >{{ sumRatefn(scope.row ,tableData1,'goodsNum','goodsNumTarget',0)}}%
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="实际出库量"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.className != '合计'&&scope.row.brandName != '合计' && scope.row.realName != '合计'">{{scope.row.shipNum}}</span>
            <span v-else style="font-weight: bold;">{{scope.row | sumListfn(tableData1,'shipNum',3)}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="实际吨毛利"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.className != '合计'&&scope.row.brandName != '合计' && scope.row.realName != '合计'">{{scope.row.perShipProfit}}</span>
            <span v-else style="font-weight: bold;">{{scope.row | sumListfn(tableData1,'perShipProfit',0)}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="目标吨毛利"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.className != '合计'&&scope.row.brandName != '合计' && scope.row.realName != '合计'">{{scope.row.perShipProfitTarget}}</span>
            <span v-else style="font-weight: bold;">{{scope.row | sumListfn(tableData1,'perShipProfitTarget',0)}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="实际总毛利"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.className != '合计'&&scope.row.brandName != '合计' && scope.row.realName != '合计'">{{scope.row.shipProfit}}</span>
            <span v-else style="font-weight: bold;">{{scope.row | sumListfn(tableData1,'shipProfit',0)}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="目标总毛利"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.className != '合计'&&scope.row.brandName != '合计' && scope.row.realName != '合计'">{{scope.row.shipProfitTarget}}</span>
            <span v-else style="font-weight: bold;">{{scope.row | sumListfn(tableData1,'shipProfitTarget',0)}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="总毛利差额"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            <span  :style="{'color':scope.row.shipProfitDiff<0 ? 'red':'#606266'}" v-if="scope.row.className != '合计'&&scope.row.brandName != '合计' && scope.row.realName != '合计'">{{scope.row.shipProfitDiff}}</span>
            <span v-else style="font-weight: bold" :style="{'color': sumDifffn(scope.row,tableData1,'shipProfit','shipProfitTarget',3) < 0 ? 'red' :'#606266'}">{{ sumDifffn(scope.row,tableData1,'shipProfit','shipProfitTarget',3)}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="总毛利完成率"
          min-width="150"
          align="center">
          <template slot-scope="scope">
            <span
              v-if="scope.row.className != '合计'&&scope.row.brandName != '合计' && scope.row.realName != '合计'"
              :style="{'color':scope.row.shipProfitRate < 100 ? 'red' : '#606266'}"
            >{{scope.row.shipProfitRate}}%</span>
            <span v-else style="font-weight: bold;"
                  :style="{'color':sumRatefn(scope.row,tableData1,'shipProfit','shipProfitTarget',0) < 100 ? 'red' : '#606266'}">
              {{ sumRatefn(scope.row,tableData1,'shipProfit','shipProfitTarget',0)}}%
            </span>
          </template>
        </el-table-column>


      </el-table>
    </div>


  </div>
</template>
<script>
import {pgoodsSaleNumAnalysis,goodsCategoryList} from '@/api/data.js'
import {getOrderUsersList} from '@/api/partner.js'
import store from '@/store'
import { mapGetters } from 'vuex'
import { formatDate } from '@/utils/date.js';

const defaultListQuery={
  "month" : "",
  "goodsClass" : "", //品类
  "brandName" : "",   //厂家
  userIds:[]
};



export default {
  name: "index",
  data(){
    return {
      roles:store.getters.roles ? store.getters.roles : [],
      props:{multiple: true,label:'value',value:'label',emitPath:false},
      listQuery1: JSON.parse(JSON.stringify(defaultListQuery)),
      tableData1: [],
      count1: 0,
      listLoading1: false,
      data:[],
      userList:[],
      classList:[],
      btnLoading:false,
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
    pGoodsSaleNumAnalysisExport(){
      if (this.roles.indexOf("pGoodsSaleNumAnalysisExport") != -1) {
        return true
      } else {
        return false
      }
    },
  },
  created() {
    this.getUserList()
    this.getClassList()
    this.listQuery1.month = this.getMonth('month')
    if(this.$route.query.dataMonth){
      this.listQuery1.month = this.$route.query.dataMonth
    }
    if(this.$route.query.dataGoodsClass){
      this.listQuery1.goodsClass = this.$route.query.dataGoodsClass
    }
    if(this.$route.query.dataBrandName){
      this.listQuery1.brandName = this.$route.query.dataBrandName
    }
    if(this.$route.query.dataUserIds){
      let userIds = this.$route.query.dataUserIds.split(",")
      this.listQuery1.userIds = userIds.map(item => Number(item));
    }
    this.getList1();
  },
  filters: {
    sumListfn(item,list,key,num){
      let sumList = []
      let sum = 0
      if(item.brandName == '合计'){
        sumList = list.filter((el)=>{
          return el.userId == item.userId && el.classId == item.classId
        })
      }else if(item.realName == '合计'){
        sumList = list.filter((el)=>{
          return el.classId == item.classId
        })
      }else if(item.className == '合计'){
        sumList = list
      }
      sum = sumList.reduce((acc, cur) => acc + (cur[key] || 0), 0);
      if(key.indexOf('perShipProfit') != -1){
        let goodsNumkey,shipProfitKey
        if(key == 'perShipProfitTarget'){
          goodsNumkey = 'goodsNumTarget';
          shipProfitKey = 'shipProfitTarget'

        }else if(key == 'perShipProfit'){
          goodsNumkey = 'shipNum';
          shipProfitKey = 'shipProfit'
        }
        let sumShipProfit = sumList.reduce((acc, cur) => acc + (cur[shipProfitKey] || 0), 0);
        let sumGoodsNum = sumList.reduce((acc, cur) => acc + (cur[goodsNumkey] || 0), 0);
        if(sumGoodsNum == 0){
          return 0
        }
        return ((sumShipProfit/sumGoodsNum).toFixed(num))*1
      }
      return (sum.toFixed(num))*1
    },
  },
  methods:{
    downloadExcel(){
      this.listQuery1.brandName = this.listQuery1.goodsClass ? this.listQuery1.brandName : ''
      let listQuery = JSON.parse(JSON.stringify(this.listQuery1));
      listQuery.userIds=listQuery.userIds.join(",")
      let params = JSON.parse(JSON.stringify(listQuery));
      params.isExport = 1;
      delete params.pageNum;
      delete params.pageSize;
      this.btnLoading = true;
      pgoodsSaleNumAnalysis(params).then((res)=>{
        this.btnLoading = false;
        require.ensure([], () => {
          const { export_json_to_excel } = require('sheet/Export2Excel');
          const tHeader = res.title;
          const filterVal = res.columns;
          const list = res.list;
          const data = this.formatJson(filterVal, list);
          export_json_to_excel(tHeader, data, res.fileName);
        })
      }).catch(()=>{
        this.btnLoading = false;
      })
    },


    //下载表格数据格式化
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    tableRowClassName({row, rowIndex}) {
      if (row.brandName == '合计') {
        return 'sum-row';
      }else if (row.realName == '合计') {
        return 'success-row';
      }else if (row.className == '合计') {
        return 'warning-row';
      }
      return '';
    },
    sumRatefn(item,list,actualkey,targetkey,num){
      let sumList = []
      let sumActual = 0
      let sumTarget = 0
      if(item.brandName == '合计'){
        sumList = list.filter((el)=>{
          return el.userId == item.userId && el.classId == item.classId
        })
      }else if(item.realName == '合计'){
        sumList = list.filter((el)=>{
          return el.classId == item.classId
        })
      }else if(item.className == '合计'){
        sumList = list
      }
      sumActual = sumList.reduce((acc, cur) => acc + (cur[actualkey] || 0), 0);
      sumTarget = sumList.reduce((acc, cur) => acc + (cur[targetkey] || 0), 0);
      if(sumTarget == 0){
        return 0
      }
      return ((sumActual/sumTarget*100).toFixed(num))*1
    },
    sumDifffn(item,list,actualkey,targetkey,num){
      let sumList = []
      let sumActual = 0
      let sumTarget = 0
      if(item.brandName == '合计'){
        sumList = list.filter((el)=>{
          return el.userId == item.userId && el.classId == item.classId
        })
      }else if(item.realName == '合计'){
        sumList = list.filter((el)=>{
          return el.classId == item.classId
        })
      }else if(item.className == '合计'){
        sumList = list
      }
      sumActual = sumList.reduce((acc, cur) => acc + (cur[actualkey] || 0), 0);
      sumTarget = sumList.reduce((acc, cur) => acc + (cur[targetkey] || 0), 0);
      return ((sumActual-sumTarget).toFixed(num)) * 1
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        if (row.isHb1) {
          return {
            rowspan: row.hb1Num,
            colspan: 1
          };
        }else if (row.isHbcol1) {
          return {
            rowspan: 1,
            colspan: 3
          };
        }else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }else if(columnIndex === 1){
        if (row.isHb2) {
          return {
            rowspan: row.hb2Num,
            colspan: 1
          };
        }else if (row.isHbcol2) {
          return {
            rowspan: 1,
            colspan: 2
          };
        }else if(!row.isHb1){
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }else if(columnIndex === 2 &&(row.isHbcol1 || row.isHbcol2) ){
        return {
          rowspan: 0,
          colspan: 0
        };
      }
    },
    getClassList(){
      goodsCategoryList().then((res)=>{
        this.classList = res
      })
    },
    //获取本月时间
    getMonth(type){
      let now = new Date();
      // 获取当前月份和年份
      const month = now.getMonth();
      const year = now.getFullYear();
      // 计算本月第一天的日期
      const startOfMonth = new Date(year, month, 1);
      // 计算下个月第一天的日期，然后减去一天得到本月的最后一天
      const startOfNextMonth = new Date(year, month + 1, 1);
      const endOfMonth = new Date(startOfNextMonth);
      endOfMonth.setDate(startOfNextMonth.getDate() - 1);
      if(type){
        return formatDate(new Date(startOfMonth), 'yyyy-MM')
      }
      return [formatDate(new Date(startOfMonth), 'yyyy-MM-dd'),formatDate(new Date(endOfMonth), 'yyyy-MM-dd')]
    },
    getUserList(){
      getOrderUsersList({departmentId:3,status:1}).then((res)=>{
        this.userList = res;
      })
    },
    newList(list){
      let data = list.sort((a, b) => {
        if (a.classId !== b.classId) {
          return a.classId - b.classId;  // 第一排序属性（升序）
        } else {
          return a.userId - b.userId;  // 第二排序属性（降序）
        }
      });

      let classList1  = this.countByMultipleProps(data,['classId','userId'])
      classList1.forEach((el)=>{
        if(el.count > 1){
          let fristIndex = data.findIndex((ee)=>{
            return ee.userId == el.userId && el.classId == ee.classId
          })
          data.splice(fristIndex+el.count, 0, {classId:Number(el.classId),userId:Number(el.userId),brandName:'合计',brandId:''})
        }
      })
      let classIdtList2  = this.countByMultipleProps(data,['classId'])
      classIdtList2.forEach((el)=>{
        let fristIndex = data.findIndex((ee)=>{
          return ee.classId == el.classId&& el.classId == ee.classId
        })
        data.splice(fristIndex+el.count, 0, {classId:Number(el.classId),userId:'',realName:'合计',brandName:'',brandId:'',isHbcol2:true})
      })
      let classIdtList2ListNew = this.countByMultipleProps(data,['classId'])
      let classList1New = this.countByMultipleProps(data,['classId','userId'])
      let classIdIndexs = []
      let userIdIndexs = []
      classIdtList2ListNew.forEach((el)=>{
        let i = data.findIndex((ee)=>{
          return ee.classId == el.classId
        })
        classIdIndexs.push(i)
      })
      classList1New.forEach((el)=>{
        if(el.userId){
          let i = data.findIndex((ee)=>{
            return ee.userId == el.userId && el.classId == ee.classId
          })
          userIdIndexs.push(i)
        }
      })
      data.forEach((el,index)=>{
        if(classIdIndexs.indexOf(index) != -1){
          let departmentItem = classIdtList2ListNew.find((item)=>{
            return item.classId == el.classId
          })
          el.isHb1 = true
          el.hb1Num =departmentItem.count
        }
        if(userIdIndexs.indexOf(index) != -1){
          let groupItem = classList1New.find((item)=>{
            return item.userId == el.userId && el.classId == item.classId
          })
          el.isHb2 = true
          el.hb2Num =groupItem.count
        }
      })
      data.push({
        classId:'',userId:'',realName:'',brandName:'',brandId:'',className:'合计',isHbcol1:true
      })
      return data
    },
    //统计相同品类，相同采购，厂家数量
    countByMultipleProps(arr, props) {
      const countMap = arr.reduce((acc, cur) => {
        const key = props.map(prop => cur[prop]).join('|'); // 例如 "1|NEW"
        acc[key] = (acc[key] || 0) + 1;
        return acc;
      }, {});
      return Object.entries(countMap).map(([key, value]) => ({
        ...Object.fromEntries(key.split('|').map((v, i) => [props[i], v])),
        count: value
      }))
    },


    //获取列表
    getList1(){
      this.listLoading1 = true;
      this.listQuery1.brandName = this.listQuery1.goodsClass ? this.listQuery1.brandName : ''
      let listQuery = JSON.parse(JSON.stringify(this.listQuery1));
      listQuery.userIds=listQuery.userIds.join(",")
      pgoodsSaleNumAnalysis(listQuery).then(response => {
        this.tableData1 = this.newList(response);
        this.count1 = response.count;
        this.listLoading1 = false;
      }).catch(()=>{
        this.listLoading1 = false;
      });
    },

    handleSizeChange1(val){
      this.listQuery1.pageNum = 1;
      this.listQuery1.pageSize = val;
      this.getList1();
    },
    handleCurrentChange1(val){
      this.listQuery1.pageNum = val;
      this.getList1();
    },

    handleSearchList1(){
      this.listQuery1.pageNum = 1;
      this.getList1();
    },


  },
}
</script>

<style>
.el-table .sum-row{
  background: #f5f7fa
}
.el-table .warning-row {
  background: #fdf5e6;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>
